package com.zy.rpc.server.transport.impl;
//
//import com.zy.rpc.common.codec.ResponseCodec;
import com.zy.rpc.common.codec.RpcDecoder;
import com.zy.rpc.common.codec.RpcEncoder;
//import com.zy.rpc.common.codec.RpcQuestCodec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import com.zy.rpc.server.handle.RpcHandle;
import com.zy.rpc.server.transport.RpcServer;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetAddress;

/**
 * @author zy
 * @date 2023/4/23 19:03
 */
public class NettyRpcServer implements RpcServer {

//    private  final RpcQuestCodec rpcQuestCodec =new RpcQuestCodec();
//    private  final ResponseCodec responseCodec =new ResponseCodec();
    @Override
    public void Start(int port)   {
        System.out.println("服务器启动");
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
                            channel.pipeline().addLast(new RpcEncoder());
                            channel.pipeline().addLast(new RpcDecoder());
                            channel.pipeline().addLast(new RpcHandle());
                        }

                    })
                    .childOption(ChannelOption.SO_KEEPALIVE,true);
            ChannelFuture channelFuture = serverBootstrap.bind(InetAddress.getLocalHost().getHostAddress(), port).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
        }  finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }


    }
}
